package com.pp.ent.util.asynctask;

/**
 * Created by dengqu on 2017/3/2.
 */

import android.os.HandlerThread;
import android.os.Looper;

import com.pp.ent.base.common.SafeHandlerDispatch;

import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

public final class ScheduledTask
{
    private volatile Looper mTaskLooper;
    private volatile SafeHandlerDispatch mTaskHandler;
    HandlerThread thread;
    private Timer timer;
    private static final ScheduledExecutorService schedule = Executors.newScheduledThreadPool(1);

    private ScheduledTask()
    {
        this.thread = new HandlerThread("ScheduledTask");
        this.thread.start();

        this.mTaskLooper = this.thread.getLooper();
        this.mTaskHandler = new SafeHandlerDispatch(this.mTaskLooper);

        this.timer = new Timer();
    }

    private static class SingletonHolder
    {
        public static final ScheduledTask instance = new ScheduledTask();
    }

    public static ScheduledTask getInstance()
    {
        return SingletonHolder.instance;
    }

    public boolean scheduledDelayed(Runnable command, long delay)
    {
        this.mTaskHandler.removeCallbacks(command);
        return this.mTaskHandler.postDelayed(command, delay);
    }

    public boolean scheduledAtTime(Runnable command, long uptimeMillis)
    {
        this.mTaskHandler.removeCallbacks(command);
        return this.mTaskHandler.postAtTime(command, uptimeMillis);
    }

    public void removeCallbacks(Runnable command)
    {
        this.mTaskHandler.removeCallbacks(command);
    }

    public boolean isInterrupted()
    {
        if (this.thread == null) {
            return false;
        }
        return this.thread.isInterrupted();
    }

    public ScheduledFuture<?> schedule(Runnable command, long delay, long period)
    {
        return schedule.scheduleAtFixedRate(command, delay, period, TimeUnit.MILLISECONDS);
    }

    public void scheduleByTimer(TimerTask task, long delay, long period)
    {
        this.timer.schedule(task, delay, period);
    }
}
